define(["avalon","./utils/config","./utils/i18n"], function(avalon,config,i18n){
	var Global = {Site:""};
	
	
    var api = {
        collectionsName:config.debug? "collections":"list", /// even res.data.xxxsection
        guidName: {
            webName:"guid",
            backEndName: "id"
        },
        titleName: config.debug? "title" :"name",
        order:{
            byRecommended:0,
            byLatest:1,
            byHot:2,
            byAttention:3
        },
        getVideos: {
            type: "videos",
			url:"json/video.action?IsWeiKe=0"// order by, size, ....
		},
		getVideo:{
			type: "video",
			url:"./json/videoId.action"
		},
        getRegister:{
            type:"",
            url:"webservice/bizLiveList.action"
        },
        delRegister:{
            type:"",
            url:"webservice/bizLiveItemDelete.action"
        },
		getSearch:{
			type: "search",
			url:"./json/search.action"
        },
        getVideoPlay:{
        	type: "video.comment",
        	url:"./json/videoplay.action"
        },
        getAlbums: {
            type: "albums",
            url: "json/album.action"
        },

		getAlbum: {
			type:"albums.title",
			url:"json/albumId.action"
		},
        getWeikes: {
            type: "weikes",
            url: "json/video.action?IsWeiKe=1"
        },
        // getAlbumsComment: {
        // 	type:"albums.comment",
        // 	url:"./api/albums.json"
        // },
        getLives: {
            type: "lives",
            url: "json/live.action"
        },
        getLive: {
            type: "live",
            url: "json/liveId.action"
        },
        getLiveuri: {
            type: "live",
            url:"json/recordEquipmentState.action"
        },
        getOnlines: {
            type: "onlines",
            url: "json/online.action"
        },
        getOnline: {
            type: "online",
            url: "json/onlineId.action"
        },
        getOnlineuri: {
            type: "online",
            url:"json/recordEquipmentState.action"
        },
        getCategories: {
            type: "categories",
            url: "json/category.action"
        },
        getGrade: {
            type: "grade",
            url: "json/grade.action"
        },
        getVideoResemble:{
            type: "videos.item",
            url:"json/resembleVideoId.action"
        },
        getVideoTimeInfo:{
            type:"video.timeinfo",
            url:"json/videoTimeInfo.action"
        },
        getAlbumsLevel:{
            type:"albums.level",
            url:"json/albumLevel.action"
        },
        getVideoSW:{
            type:"video.sw",
            url:"json/videoSW.action"
        },
        getVideoST:{
            type:"",
            url:"json/videoPattern.action"
        },
        getAlbumVideo:{
            type:"albums.item.play",
            url:"json/albumVideo.action"
        },
        getLiveAttachment:{
            type:"live",
            url:"json/liveAttachment.action"
        },
        getOnlinesState:{
            type:"onlines",
            url:"json/recordEquipmentStateList.action"
        },
        getSetting:{
            type: "setting",
            url:"json/setting.action"
        },
        getNotices:{
            type:"notices",
            url:"json/notice.action"
        },
        getNotice:{
            type:"notice",
            url:"json/noticeId.action"
        },
        getNoticesType:{
            type:"notices.type",
            url:"json/noticeType.action"
        },
        setLivePv:{
            type:"pv",
            url:"pv/saveLive.action"
        },
        setPagePv:{
            type:"pv",
            url:"pv/savePage.action"
        },
        setVideoPv:{
            type:"pv",
            url:"pv/saveVideo.action"
        },
        setAlbumPv:{
            type:"pv",
            url:"pv/saveAlbum.action"
        },
        getGradeList:{
            type:"getGradeList",
            url:"webservice/bizGradeListWithSection.action"
        },
        getCategories:{
            type:"getGategories",
            url:"webservice/bizCategoryListWithSection.action"
        },
        getRecordeEquimentTimeList:{
            type:"timeList",
            url:"webservice/pubRecordEquipmentTimeList.action"
        },
        setLiveItemAdd:{
            type:'setLiveItemAdd',
            url:'webservice/bizLiveItemAdd.action'
        },
        getRecordVideoList:{
            type:'RecordVideoList',
            url:'webservice/bizRecordVideoList.action'
        },
        getPubRecordEquipmentList:{
            type:'pubRecordEquipmentList',
            url:'webservice/pubRecordEquipmentListApply.action'
        },

        
        getItems: function(opts, cb) {
            // method 
            // type: video|album|online
            // query:
            // orderby: 
            // category | grade | school |

            // page-index page-size

            // stub

            // console.log(opts)
            if(config.debug){


                var urls = {
                	"videos": require("./api/videos.json"),
                	"video": require("./api/video.json"),
                    
                	"orders": require("./api/orders.json"),

                	"search": require("./api/search.json"),

                	"lives": require("./api/lives.json"),
                	"live": require("./api/live.json"),
                	"weikes": require("./api/weikes.json"),
                	"albums": require("./api/albums.json"),
                	"albums.item":  require("./api/albums/album.json"),
                	"albums.item.play":  require("./api/albums/album.json"),//

                    "grade": require("./api/grade.json"),
                	"categories": require("./api/categories.json")
                };

                var url = urls[opts.method.type];


                return new Promise(function (rs) {
                             require.ensure([], function () {
                              	rs(url)
                          })
                      })
                      .done(function(res){
                      	// console.log("service results: " ,opts, res);
                            res = handleData(res,opts);
                           	cb(res)
                         });


            }else{

                return $.ajax({
                    cache: false,
                    type: "GET",
                    url: avalon.vmodels.app.$sitePath+"/"+opts.method.url,
                    data:opts.query,
                       success: function (res) {
                            if(opts.ingore){
                                cb(res)
                                return;
                            }
                            if(res.success){
                                if(opts.handleData != false)
                                    res = handleData(res,opts);
                            }else{
                                res = {
                                    success:res.success,
                                    errorCode:res.errorCode,
                                    message: res.message
                                }

                                // avalon.router.redirect("errors")  
                            }
                            
                            cb(res);
                            setTimeout(function(){
                                $(window).trigger('resize');
                            },100)
                    }
                });

            }

        },
        postUserViewHistory: function(parmas, cb) {
            // var _params = {
            // 	pos: null,
            // 	duration: null,
            // 	ParentAlbum: null,
            // 	ParentPublicClass: null,
            // 	VideoGuid: null,
            // 	ParentPublicClassGuid:null;
            // }
            avalon.mix(this, params);

            var data = "";
            if (ParentAlbum != null) {

                data = "Type=1&VideoGuid=" + VideoGuid + "&AlbumGuid=" + ParentAlbum.Guid + "&Seconds=" + pos + "&VideoLen=" + duration;
              }else if (ParentPublicClass != null)
                     {

                data = "Type=2&VideoGuid=" + VideoGuid + "&AlbumGuid=" + ParentPublicClassGuid + "&Seconds=" + pos + "&VideoLen=" + duration;

                     }
                     else
                     {

                data = "Type=0&VideoGuid=" + VideoGuid + "&Seconds=" + pos + "&VideoLen=" + duration;

            }

			$.ajax(
               {
                cache: false,
                type: "POST",
                url: Global.Site + "/Tools/Video/UserViewHistory.aspx?rnd=" + Math.random() * 10,
                data: data,
                async: false,
                dataType: 'json',
                success: function(result) {
                    cb(result);
                },
                error: function(result) {

                }
            });
        },
        getUserViewHistory: function(params, cb) {
            var guid = params.guid;
            $.ajax({
                cache: false,
                type: "POST",
                url: Global.Site + "/Tools/Video/UserViewHistoryGet.aspx?VideoGuid=" + guid,
                success: function(result) {
                    cb(result);
                }
            });
        }

    }

    function handleData(res,opts){
        var tmpSearch = {};
        if(opts.method == api.getGrade || opts.method == api.getCategories){

            tmpSearch = {}
            tmpSearch[api["collectionsName"]] = [];
            var defaultItem = {
                name:i18n.gettext("no limit")
            }
            defaultItem[api["guidName"]["webName"]] = 0;
            tmpSearch[api["collectionsName"]].push(defaultItem);

            var secondlevel = opts.method == api.getGrade ? "gradeSection":"categorySection";
            var thirdlevel =  opts.method == api.getGrade ? "grades":"categories";

            _.each(res.data[secondlevel],function(re){

                _.each(re[thirdlevel],function(r){
                
                    var item = {
                        "name":r[api.titleName]
                    }
                    item[api["guidName"]["webName"]] = r[api.guidName.backEndName];
                    tmpSearch[api["collectionsName"]].push(item)
                })
            })

            return tmpSearch;
        }


        if(opts.method == api.getAlbumsLevel||opts.method == api.getNoticesType){
            tmpSearch = {}
            tmpSearch[api["collectionsName"]] = [];
            var defaultItem = {
                name:i18n.gettext("no limit")
            }

            defaultItem[api["guidName"]["webName"]] = 0;
            tmpSearch[api["collectionsName"]].push(defaultItem);

                _.each(res['list'],function(r){
                
                    var item = {
                        "name":r[api.titleName]
                    }
                    item[api["guidName"]["webName"]] = r[api.guidName.backEndName];
                    tmpSearch[api["collectionsName"]].push(item)
                })
    

            return tmpSearch;

        }

        if(opts.method.type == api.getAlbumVideo.type){

            _.each(res[api.collectionsName], function(re){
                re.ParentId = opts.query.albumId;
            })

        }



        if(config.debug){
            if(!res.query) res.query = {};
            res.query.recordCount = res.total;
            res.query.pageIndex = res.pageIndex;
            res.query.pageSize = res.perPages || 8;
        }


        
        if(_.isArray(res)){
            if(_.has(res[0],api.collectionsName)){
                _renderHref(res[0][api.collectionsName], opts.method.type);
            }else{
                _renderHref(res, opts.method.type);
            }
        }else{
            if(_.has(res,api.collectionsName)){
                _renderHref(res[api.collectionsName], opts.method.type);
            }else{
                _renderHref(res, opts.method.type);
            }
         }

         return res;
    }




    function _renderHref(results,type){
                // albums/abc/play

        var states = avalon.router.routingTable["get"];
        var i = states.length -1 , matchState;


        while (i > -1) {
            var el = states[i];
            if (type == el.stateName) {
                matchState = el;
                break;
            }
            i -= 1;

        }

        if (matchState) {
            //{itemID} {vid}
            var chains = matchState.url.split("/"),
                regexs = [];
            braces = /{\w+}/;

            regexs = _.filter(chains, function(c) {
                return braces.exec(c);
            })



            // results json awalys via []
            results = results||[];
            _.each(results, function(v) {

                //@TODO hasOwnProperty
                if(_.has(v,api.guidName.backEndName)){

                    if (v.href == undefined) {

                        if (regexs.length == 0) {
                            v.href = "#!"+  matchState.url + "/" + v[api.guidName.backEndName];
                        } else {

                            var href = matchState.url.replace(regexs[1]||regexs[0],v[api.guidName.backEndName]);

                            if(regexs.length == 2 && v.ParentId){
                                href = href.replace(regexs[0],v.ParentId)
                            }

                          
                             v.href = "#!"+ href;


                            //   fuck not in sublevel
                            // _.forIn(v, function(k) {
                            //     if (_.isArray(k)) {
                            //         _.each(k, function(val) {
                            //             if(val && _.has(val,api.guidName.backEndName)){
                            //                 val.href = "#!"+  matchState.url.replace(regexs[0],v[api.guidName.backEndName]) +"/play/"+ val[guid];
                            //             }
                            //         })
                            //     }
                            // });
                        }
                    }


                } else {
                    v.href = "#!" + matchState.url;
                }


            })

        }
    }

    return api;
})
